package com.czl.module_base.http;


import android.util.Log;

import com.czl.module_base.system.HttpConstants;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * @author xubin
 * @date on 2018/9/14  18:56
 */
public class RetryWithDelay implements Function<Observable<Throwable>, ObservableSource<?>> {

    public final String TAG = this.getClass().getSimpleName();
    /**
     * 最大重试次数
     */
    private final int maxRetries;
    /**
     * 重试间隔时间
     */
    private final int retryDelaySecond;
    private int retryCount;

    public RetryWithDelay(int maxRetries, int retryDelaySecond) {
        this.maxRetries = maxRetries;
        this.retryDelaySecond = retryDelaySecond;
    }

    public RetryWithDelay() {
        this.maxRetries = HttpConstants.MAX_RETRIES;
        this.retryDelaySecond = HttpConstants.RETRY_DELAY_SECOND;
    }

    @Override
    public ObservableSource<?> apply(Observable<Throwable> throwableObservable) {
        return throwableObservable
                .flatMap((Function<Throwable, ObservableSource<?>>) throwable -> {
                    if (++retryCount < maxRetries) {
                        Log.w(TAG, "Observable get error, it will try after " + retryDelaySecond
                                + " second, retry count " + retryCount);
                        return Observable.timer(retryDelaySecond,
                                TimeUnit.SECONDS);
                    }
                    return Observable.error(throwable);
                });
    }
}
